package zzzhc.image.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import zzzhc.image.recognize.Filter;
import zzzhc.image.recognize.FilterManager;
import zzzhc.image.recognize.ImageRecognizer;
import zzzhc.image.recognize.SerializeUtil;
import zzzhc.image.recognize.TokenRecognizer;

public class AppModel {
	private CapturePanelModel capturePanelMode = new CapturePanelModel();

	private OpPanelModel opPanelModel = new OpPanelModel();

	private TrainerPanelModel trainerPanelModel = new TrainerPanelModel();

	private ImageRecognizer imageRecognizer = new ImageRecognizer();

	private boolean saved = false;

	private static AppModel instance;

	private AppModel() {
		opPanelModel.setCaptureTableModel(capturePanelMode
				.getCaptureTableModel());
		trainerPanelModel.setOpPanelModel(opPanelModel);
	}

	public synchronized static AppModel getInstance() {
		if (instance == null) {
			instance = new AppModel();
		}
		return instance;
	}

	public void clear() {
		opPanelModel.getFilterManager().clear();
		imageRecognizer.setFilter(null);
		imageRecognizer.setTokenRecognizer(null);
		saved = false;
	}

	public ImageRecognizer getImageRecognizer() {
		return imageRecognizer;
	}

	public void setFilter(Filter filter) {
		imageRecognizer.setFilter(filter);
	}

	public void setTokenRecognizer(TokenRecognizer tr) {
		imageRecognizer.setTokenRecognizer(tr);
	}

	public OpPanelModel getOpPanelModel() {
		return opPanelModel;
	}

	public CapturePanelModel getCapturePanelModel() {
		return capturePanelMode;
	}

	public TrainerPanelModel getTrainerPanelModel() {
		return trainerPanelModel;
	}

	public void save(File f) throws IOException {
		FileOutputStream out = new FileOutputStream(f);
		SerializeUtil.saveImageRecognizer(AppModel.getInstance()
				.getImageRecognizer(), out);
		out.close();
		saved = true;
	}

	public boolean isSaved() {
		return saved;
	}

	public void load(File f) throws IOException {
		FileInputStream in = new FileInputStream(f);
		ImageRecognizer ir = SerializeUtil.loadImageRecognizer(in);
		this.imageRecognizer = ir;
		if (ir.getFilter() instanceof FilterManager) {
			opPanelModel.setLastFilterManager((FilterManager) ir.getFilter());
		}
		in.close();
	}

}
